/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.item

import org.springframework.transaction.annotation.*
import org.hibernate.Hibernate
import org.ibiblio.terasaur.item.Item
import org.ibiblio.terasaur.user.User

class BrowseService {
    def sessionFactory // injected hibernate SessionFactory

    /**
     * Get list of published, non-deleted Items, sorted by popularity.  Returns
     * a Map with results and totalCount keys.
     *
     * @return Map
     */
    def popular(Map listParams) {
        def results
        def totalCount
        def sql
        def query

        def session = sessionFactory.currentSession
        String baseQuery = "SELECT this_.id, this_.version, this_.date_created, this_.deleted, \
                this_.description, this_.identifier, this_.language, this_.last_updated, \
                this_.license, this_.owner_id, this_.published, this_.title, this_.type, \
                this_.collection_id, \
                COALESCE(SUM(s.seeds + s.peers), 0) AS peer_count \
            FROM ts_item this_ \
            LEFT JOIN ts_torrent t ON (t.item_id = this_.id) \
            LEFT JOIN ts_torrent_stats s ON (s.info_hash = t.info_hash) \
            WHERE this_.deleted = false \
                AND this_.published <= NOW() \
            GROUP BY this_.id, this_.version, this_.date_created, this_.deleted, \
                this_.description, this_.identifier, this_.language, this_.last_updated, \
                this_.license, this_.owner_id, this_.published, this_.title, this_.type, \
                this_.collection_id \
            HAVING COALESCE(SUM(s.seeds + s.peers), 0) > 0"

        // Get results total count
        query = "SELECT COUNT(1) FROM ( " + baseQuery + ") AS total_count"
        sql = session.createSQLQuery(query)
            .addScalar("COUNT", Hibernate.LONG)
            .setCacheable(true)
        results = sql.list()
        totalCount = results[0]

        // Get item list
        query = baseQuery + " ORDER BY peer_count DESC, this_.published DESC"
        sql = session.createSQLQuery(query)
            .addEntity(org.ibiblio.terasaur.item.Item)
            .setFirstResult(listParams['offset'])
            .setMaxResults(listParams['max'])
            .setCacheable(true)
        results = sql.list()

        Map m = [
            'results': results,
            'totalCount': totalCount
            ]
        return m
    }

    def myItems(Map listParams, User user) {
        def c = Item.createCriteria()
        def results = c.list(listParams) {
            eq("deleted", listParams.showDeleted)
            eq("owner", user)
            order("dateCreated", "desc")
            cache(true)
        }
        Map m = [
            'results': results,
            'totalCount': results.totalCount
            ]
        return m
    }
}
